<?php

namespace app\admin\logic\zhxy;

use app\admin\logic\ZHXY;
use app\admin\logic\zhxy\task\Inst;
use app\admin\logic\zhxy\task\Task;
use app\admin\logic\zhxy\task\TaskLog;
use app\common\library\Log;
use app\common\library\Logger;
use think\Cache;

class TaskApi
{

    protected $thirdparty_id = 0;
    protected $token         = '';


    public function __construct()
    {
        $this->thirdparty_id = config('zhxy.thirdparty_id') ?? 0;
        $this->token         = (new \app\admin\logic\zhxy\GetAccessToken())->get_token();

    }


    /**
     * 保存事项列表
     *
     * @return void
     */
    public function push_apps($appid, $appname)
    {
        $url        = config('zhxy')['push-apps'];
        $conversion = true;
        $data       = [
            'conversion' => $conversion,
            'apps'       => [
                [
                    'id'            => $appid,
                    'name'          => $appname,
                    'thirdparty_id' => $this->thirdparty_id
                ]
            ],

        ];
//        dump($data);
        $re = $this->send_msg($url, $data);
        if (!$re[0]) {
            Logger::error("error", [ $url, $data, $re ]);
        }

        return $re;
    }


    /**
     * 我的实例
     *
     * @param $status
     * @param $appid
     * @return array
     */
    public function inst_list($number = '', $status = 0)
    {
        $url  = '/open/task-center/inst';
        $data = [
            'access_token'=>$this->token,
            'status' => $status
        ];
        if ($number) {
            $data['number'] = $number;
        }
        $re = $this->send_msg($url, $data);
        if (!$re[0]) {
            Logger::error("error", [ $url, $data, $re ]);
        }

        return $re;
    }

    /**
     * 保存任务操作记录
     *
     * @return void
     */
    /**
     * @param string $number 工号
     * @param string $task_id 任务 id (审核ID)
     * @param string $inst_id 实例 id  (采购计划ID)
     * @param string $node_name 节点名称
     * @param string $operation_desc 操作名称
     * @param string $comment 审批意见(备注信息)
     * @param string $created 2021-06-08 12:00:00
     * @return void
     */
    public function push_task_log(TaskLog $taskLog)
    {
        $taskLog->thirdparty_id = $this->thirdparty_id;

        $url  = config('zhxy.push-task-log');
        $data = $taskLog->toArray();

//        dd($url,$data);
        return $this->send_msg($url, [ $data ]);
    }


    public function createApp($inst, $appname)
    {

        $name = "采购管理系统 ";

        $appname = "[$name]" . $appname;
//        dd($appname);

        $created_key = 'zhxy_create_' . (string)$inst->app_id;
        $created     = Cache::get($created_key);

        if (!$created) {
            // 没有创建app
            $re = $this->push_apps($inst->app_id, $appname);
            if ($re[0]) {
                Cache::set($created_key, 1, 3600 * 48);
            }
        }
    }

    /**
     * 推送任务变更
     *
     * @param Inst $inst 实例数据
     * @param Task $task 任务数据
     * @param string $appname 应用名字
     * @return array
     */
    public function push_task(Inst $inst, $task, $appname)
    {

        $inst->thirdparty_id = $this->thirdparty_id;
        if ($task) {
            $task->thirdparty_id = $this->thirdparty_id;
        }
        $this->createApp($inst, $appname);


        $url  = config('zhxy.push-task');
        $data = [
            'inst_data' => [
                $inst->toArray()
            ]
        ];
        if ($task) {
            $data['task_data'] = [ $task->toArray() ];
        }

        return $this->send_msg($url, $data);
    }

    /**
     * 发送消息
     *
     * @param $url
     * @param $data
     * @return array
     */
    private function send_msg($url, $post_data): array
    {

        $domain  = config('zhxy.shool_url');
        $urlFull = $domain . $url . '?access_token=' . $this->token;
        Logger::debug("taskapi send ", [ $url, $post_data ]);
        if(!ZHXY::getIsSend()){
            Logger::debug("taskapi send - no");

            return [ true, '发送成功', [] ];
        }
        $data = $this->json_post($urlFull, $post_data);

        $res = json_decode($data, true);
        Logger::debug("taskapi return  ", [ $data, $res ]);
//        dump($res);
        if ($res['e'] == 0) {
            return [ true, '发送成功', $res ];
        }

        return [ false, $res['m'], $res ];
    }


    /**
     * PHP发送Json对象数据
     *
     * @param $url 请求url
     * @param $data 发送的json字符串/数组
     * @return array
     */
    private function json_post($url, $data = NULL)
    {

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) {
            return 'data is null';
        }
        if (is_array($data)) {
            $data = json_encode($data);
        }
        // dump2($url,$data);

        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);

        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen($data),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res     = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);

        return $res;

    }


}